﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.ComponentModel;
using System.Windows.Data;
using System.Text;
using RSA;
using System.Xml.Linq;
using AOuSuisJe;

namespace AOuSuisJeWP7
{
    public partial class Login : PhoneApplicationPage
    {
        private List<ValidationError> validationErrors;
        private ValidationError credentialError;
        UserLogin userLogin;
        public Login()
        {
           
            InitializeComponent();
            userLogin = ((App)Application.Current).userLogin;
           
            validationErrors = new List<ValidationError>();
            this.DataContext = userLogin;

            //this.BindingValidationError += new EventHandler<ValidationErrorEventArgs>(Login_BindingValidationError);
        }
       
        private bool ValidateUser(string email, string password)
        {

            RSACrypto oRSA = new RSACrypto();


            var appDataXml = XElement.Load("/AOuSuisJeWP7;component/key.xml");
            oRSA.FromXmlString(appDataXml.ToString());
//Convert your  text to a byte array
            byte[] rawBytes = System.Text.Encoding.UTF8.GetBytes(password); //Encrypt your raw bytes and return the encrypted bytes
            byte[] encBytes = oRSA.Encrypt(rawBytes); //Now decrypt your encrypted bytes
            ApiUpload api = new ApiUpload();
            api.AuthenticateUser(email,encBytes);
            api.ApiCallEnded += new ApiCallEndedEventHandler(api_ApiCallEndedLogin);
            //byte[] decBytes = oRSA.Decrypt(encBytes); //Convert your decrypted bytes back to a string
            //string test = System.Text.Encoding.UTF8.GetString(decBytes, 0, decBytes.Length); 

            //AuthenticationService.AuthenticationServiceClient asc = new AuthenticationService.AuthenticationServiceClient();
            //asc.LoginCompleted += new EventHandler<AuthenticationService.LoginCompletedEventArgs>(asc_LoginCompleted);
            //asc.LoginAsync(email, password, null, true);
         
            return true;
        }

        void api_ApiCallEndedLogin(object sender, EventArgs e)
        {
            Dispatcher.BeginInvoke(() =>
            {
                if (bool.Parse((string)sender))
                {
                    userLogin.IsAuthenticate = true;
                    NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative));
                    System.IO.IsolatedStorage.IsolatedStorageSettings.ApplicationSettings.Add("login", userLogin);
                }
                else
                {
                    EmailLabel.Foreground = new SolidColorBrush(Colors.Red);
                    PasswordLabel.Foreground = new SolidColorBrush(Colors.Red);

                    ValidationSummary.Text = "Adresse ou mot de passe incorrect.";

                }
            });
        }

        void asc_LoginCompleted(object sender, AuthenticationService.LoginCompletedEventArgs e)
        {
            if (e.Result)
            {
                userLogin.IsAuthenticate = true;
                NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative));
                System.IO.IsolatedStorage.IsolatedStorageSettings.ApplicationSettings.Add("login", userLogin);
            }
            else
            {
                EmailLabel.Foreground = new SolidColorBrush(Colors.Red);
                PasswordLabel.Foreground = new SolidColorBrush(Colors.Red);

                ValidationSummary.Text = "Adresse ou mot de passe incorrect.";

            }
        }

        private void LoginButton_Click(object sender, RoutedEventArgs e)
        {
            foreach (DependencyObject control in ContentPanel.Children)
            {
                TextBox textBox = control as TextBox;
                if (textBox != null)
                {
                    BindingExpression expr = textBox.GetBindingExpression(TextBox.TextProperty);
                    expr.UpdateSource();
                }
                PasswordBox pass = control as PasswordBox;
                if (pass != null)
                {
                    BindingExpression expr = pass.GetBindingExpression(PasswordBox.PasswordProperty);
                    expr.UpdateSource();
                }
            }
            if (validationErrors.Count > 0)
            {

            }
            else
            {
                ValidateUser(EmailTextBox.Text, PasswordTextBox.Password);
            }
        }

        private void EmailTextBox_BindingValidationError(object sender, ValidationErrorEventArgs e)
        {
            if (e.Action == ValidationErrorEventAction.Added)
            {
                EmailLabel.Foreground = new SolidColorBrush(Colors.Red);
                validationErrors.Add(e.Error);
            }
            else
            {
                EmailLabel.Foreground = new SolidColorBrush(Colors.White);
                validationErrors.Remove(e.Error);
            }
            displayErrors();
        }


        private void PasswordTextBox_BindingValidationError(object sender, ValidationErrorEventArgs e)
        {
            if (e.Action == ValidationErrorEventAction.Added)
            {
                PasswordLabel.Foreground = new SolidColorBrush(Colors.Red);
                validationErrors.Add(e.Error);
            }
            else
            {
                PasswordLabel.Foreground = new SolidColorBrush(Colors.White);
                validationErrors.Remove(e.Error);
            }
            displayErrors();
        }

        private void displayErrors()
        {
            StringBuilder errors = new StringBuilder();
            foreach (ValidationError ve in validationErrors)
            {
                errors.AppendLine(ve.ErrorContent.ToString());
            }
            ValidationSummary.Text = errors.ToString();
        }

        private void CancelButton_Click(object sender, RoutedEventArgs e)
        {
            NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative));
        }

        private void SignButton_Click(object sender, RoutedEventArgs e)
        {
            NavigationService.Navigate(new Uri("/Register.xaml", UriKind.Relative));
        }

        private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
        {
            if (userLogin.Email != null)
                NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative));
        }


    }
}